import { reactive, ref } from "vue";
import { getUserListAPI, searchUserAPI, deleteUserAPI } from "@/api/user.ts";
import { ElMessage } from "element-plus";

export default function useUserManage() {
  const userList = ref()
  const dialog = ref()
  const userNumber = ref(0)
  const phoneForm = reactive({
    phone: ''
  })
  const pagerParams = reactive({
    limit: 6,
    page: 1
  })

  // 获取用户列表
  const getUserList = async () => {
    const res = await getUserListAPI(pagerParams)
    userList.value = res.data.users
    userNumber.value = res.data.total
  }

  // 查询用户
  const searchUser = async () => {
    const res = await searchUserAPI(phoneForm)
    userList.value = res.data
  }

  // 编辑
  const EditUser = (row: any) => {
    dialog.value.init(row)
  }

  // 删除用户
  const deleteUser = async (row: any) => {
    const res: any = await deleteUserAPI(row._id)
    ElMessage({
      type: 'success',
      message: res.message
    })
    await getUserList()
  }

  // 重置列表
  const resetList = async () => {
    phoneForm.phone = ''
    await getUserList()
  }

  // 换页
  const changePage = async () => {
    await getUserList()
  }

  return {
    userNumber,
    userList,
    phoneForm,
    dialog,
    pagerParams,
    searchUser,
    resetList,
    changePage,
    EditUser,
    deleteUser,
    getUserList
  }
}
